package design.patterns.proxymode.dynamicProxy.proxy_Spring_AOP;

import design.patterns.proxymode.dynamicProxy.service.IAdviceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * java 类中一个特殊的Bean,返回代理类
 * @Description :
 * @author: cww
 * @DateTime: 2018-07-26 23:32
 */

public class ProxyFactoryBean {

    private Object target;
    private IAdviceImpl iAdvice;

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public IAdviceImpl getiAdvice() {
        return iAdvice;
    }

    public void setiAdvice(IAdviceImpl iAdvice) {
        this.iAdvice = iAdvice;
    }

    public Object getProxy() {
        Object proxy = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        /*******业务代码开始********/
                        iAdvice.beforMethod(method);
                        /*******业务代码结束********/
                        Object returnObj = method.invoke(target,args);
                        /*******业务代码开始********/
                        iAdvice.afterMethod(method);
                        /*******业务代码结束********/
                        return returnObj;
                    }
                }
        );
        return proxy;
    }
}
